package net.hvacapp.cmvrfforandroid.ui.project;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.mirror.android.common.util.StringUtils;

import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.adapter.BaseAdapterHelper;
import net.hvacapp.cmvrfforandroid.adapter.QuickAdapter;
import net.hvacapp.cmvrfforandroid.constant.Constant;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.manager.ProjectManager;
import net.hvacapp.cmvrfforandroid.ui.BaseActivity;
import net.hvacapp.cmvrfforandroid.ui.MainTabBarActivity;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetProductDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetRoomDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetSwjDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.GuidData;
import net.hvacapp.cmvrfforandroid.ui.project.model.ProjectInfoData;
import net.hvacapp.cmvrfforandroid.ui.project.model.RoomData;
import net.hvacapp.cmvrfforandroid.ui.project.model.SwjData;
import net.hvacapp.cmvrfforandroid.utils.AnnotationUtil;
import net.hvacapp.cmvrfforandroid.utils.NumberUtil;
import net.hvacapp.cmvrfforandroid.widget.CellSeperateLineView;
import net.hvacapp.cmvrfforandroid.widget.IOSAlertView;
import net.hvacapp.cmvrfforandroid.widget.ItemSelectionView;
import net.hvacapp.cmvrfforandroid.widget.ProjectActionView;
import net.hvacapp.cmvrfforandroid.widget.UserSelectionView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@EActivity(R.layout.activity_project_step5)
public class ProjectStep5Activity extends BaseActivity {

    private final int Select_Swj = 1;
    private final int Select_Swj_Xl = 2;

    @ViewById(R.id.action_view)
    ProjectActionView mActionView;


    private Dialog mProgressDlg;

    @ViewById(R.id.lv_templete)
    ListView mTempleteLv;

    private QuickAdapter<SwjData> mQuickAdapter;

    private ArrayList<RoomData> mRoomData;
    private ArrayList<SwjData> mSwjData;

    private SwjData mCurrentSwj;

    private List<GuidData> mCandiData; //可选型式



    /**
     * 页面加载完后执行
     */
    @AfterViews
    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        initViews();
        initEvent();
    }

    /***
     * 初始化视图
     */
    private void initViews() {
        mActionView.setActionInfo(ProjectManager.getInstance().getTotal(), ProjectManager.getInstance().getCurrent());
    }

    /**
     * 初始化
     */
    @Override
    public void initBoot() {
        mRoomData = new ArrayList<>();
        mSwjData = new ArrayList<>();
        mCandiData = null;

        setupToolbar(R.string.title_for_project, "室外机配置", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(AnnotationUtil.get(MainTabBarActivity.class));
            }
        });

//        int ids[] = {R.id.action_new_swj};
//        int icons[] = {R.drawable.new_project};
//        setupToolbarMenuItem(ids, icons, new String[]{"新建"}, null);
        setButton1Info("新建", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addOneProjectSWJInfo();
            }
        });


        if (mQuickAdapter == null){
            mQuickAdapter = new QuickAdapter<SwjData>(context, R.layout.swj_config_cell_item) {
                @Override
                protected void convert(final BaseAdapterHelper helper, final SwjData item) {
                    LinearLayout swjInfoLl = helper.getView(R.id.ll_swj_info);
                    swjInfoLl.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //控制显示隐藏
                            item.setClosed(!item.isClosed());
                            if (item.isClosed()) {
                                helper.setImageResource(R.id.iv_selected_mark, R.drawable.arrow_down);
                                helper.setVisible(R.id.ll_swj_content, false);
                            }
                            else {
                                helper.setImageResource(R.id.iv_selected_mark, R.drawable.arrow_up);
                                helper.setVisible(R.id.ll_swj_content, true);
                            }
                        }
                    });

                    helper.setText(R.id.tv_title, item.getName());
                    String desc = NumberUtil.formateDouble(item.getArea()) + "平米 " +
                            NumberUtil.formateDouble(item.getLoad()) + "W" + "配比率：" + NumberUtil.formateDouble(item.getPbl());
                    helper.setText(R.id.tv_description, desc);

                    TextView deleteTv = helper.getView(R.id.tv_delete);
                    deleteTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //删除

                            Map<String, Object> param = new HashMap<>();
                            param.put("siid", item.getGuidId());

                            BasicHttpClient.httpDeleteAsync(HttpConstant.HTTP_DELETE_PROJECT_ONE_SWJINFO, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetSwjDataResp>() {
                                @Override
                                public void onSuccess(GetSwjDataResp obj) {
                                    //需要重新拉取所有的系统数据
                                    mQuickAdapter.remove(item);
                                    mSwjData.remove(item);
                                }

                                @Override
                                public void onFailure(String response) {
                                    showMessage("删除室外机系统失败！");
                                }
                            });
                        }
                    });

                    //选择室外机
                    UserSelectionView selectionView = helper.getView(R.id.sel_swj);
                    selectionView.setTitleString("室外机");
                    if ( StringUtils.isEmpty(item.getSwjId()) || StringUtils.isEquals(item.getSwjId(), Constant.EMPTY_DEVICE_ID)) {
                        selectionView.setInfoString("请选择");
                    }
                    else {
                        selectionView.setInfoString(item.getXh());
                    }
                    selectionView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //选择室外机设备
                            mCurrentSwj = item;
                            Intent intent = new Intent(ProjectStep5Activity.this, AnnotationUtil.get(SelectDeviceXlActivity.class));
                            Bundle bundle = new Bundle();
                            bundle.putBoolean("multiple", false);
                            bundle.putString("tag", ProjectInfoData.MACHINE_TAG_FOR_SWJ);
                            intent.putExtras(bundle);
                            startActivityForResult(intent, Select_Swj);
                        }
                    });

                    //自动选型
                    TextView autoTv = helper.getView(R.id.tv_swj);
                    autoTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //自动选型点击
                            mCurrentSwj = item;
                            if (mCandiData != null && mCandiData.size() == 1) {
                                //只有一个系列时，直接开始自动选型
                                ProjectManager.getInstance().setProjectDefaultSeries(ProjectInfoData.MACHINE_TAG_FOR_SWJ, mCandiData.get(0).getGuidId());
                                getSwjDefaultDevice(mCurrentSwj);
                                return;
                            }
                            Intent intent = new Intent(ProjectStep5Activity.this, AnnotationUtil.get(SelectXlActivity.class));
                            Bundle bundle = new Bundle();
                            bundle.putBoolean("multiple", false);
                            bundle.putString("tag", ProjectInfoData.MACHINE_TAG_FOR_SWJ);
                            intent.putExtras(bundle);
                            startActivityForResult(intent, Select_Swj_Xl);
                        }
                    });

                    //添加房间
                    LinearLayout swjContent = helper.getView(R.id.ll_room);
                    swjContent.removeAllViews();
                    if (mRoomData.size() > 0) {
                        swjContent.setVisibility(View.VISIBLE);
                    }
                    else {
                        swjContent.setVisibility(View.GONE);
                    }

                    for (final RoomData room : mRoomData) {
                        CellSeperateLineView line = new CellSeperateLineView(ProjectStep5Activity.this);
                        swjContent.addView(line);

                        final ItemSelectionView itemView = new ItemSelectionView(ProjectStep5Activity.this);
                        itemView.setTitleString(room.getName());

                        int status = checkRoomIsSelected(room.getGuidId(), item);
                        itemView.setItemEnable(true);
                        if (status == 0) {
                            //可以选择
                            itemView.setItemSelected(false);
                        }
                        else if (status == 1) {
                            //已经选择
                            itemView.setItemSelected(true);
                        }
                        else {
                            //不可选择
                            itemView.setItemEnable(false);
                        }

                        itemView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                int status = checkRoomIsSelected(room.getGuidId(), item);

                                if (status == 1) {
                                    //取消选择
                                    for (String id : item.getRooms()) {
                                        if (StringUtils.isEquals(id, room.getGuidId())) {
                                            item.getRooms().remove(id);
                                            break;
                                        }
                                    }
                                }
                                else {
                                    //选择
                                    item.getRooms().add(room.getGuidId());
                                }

                                //提交修改
                                modifyProjectSWJInfo(item);
                            }
                        });

                        swjContent.addView(itemView);

                    }



                }
            };
        }

        mTempleteLv.setAdapter(mQuickAdapter);
    }

    /**
     * toolbar上的按钮点击事件
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_new_swj:
                addOneProjectSWJInfo();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 初始化数据
     */
    @Override
    public void initData(Intent intent) {
        loadAllRoomData();
        loadProjectSelectedSeries();
    }

    /**
     *  获取项目中选择了的系列
     */
    private void loadProjectSelectedSeries() {
        Map<String, Object> param = new HashMap<>();
        param.put("pid", ProjectManager.getInstance().getProjectData().getGuidId());
        param.put("tag", ProjectInfoData.MACHINE_TAG_FOR_SWJ);

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROJECT_PRODUCT_SERIES, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetProductDataResp>() {
            @Override
            public void onSuccess(GetProductDataResp obj) {
                // 成功
                if (obj.getGetCandidateXlsResult() != null && obj.getGetCandidateXlsResult().size() > 0) {
                    mCandiData = obj.getGetCandidateXlsResult();
                }
            }

            @Override
            public void onFailure(String response) {
//                showMessage("获取系列失败，请重试！");
            }
        });
    }


    private int checkRoomIsSelected(String rId, SwjData data) {
        for (String item : data.getRooms()) {
            if (StringUtils.isEquals(item, rId)) {
                return 1; //选中了得
            }
        }

        for (SwjData item : mSwjData) {
            for (String rm : item.getRooms()) {
                if (StringUtils.isEquals(rm, rId)) {
                    return 2; //在其他中选中了得，不可选状态
                }
            }
        }
        return 0; //还米有选中
    }




    /**
     * 页面名称
     */
    @Override
    public String getName() {
        return "";
    }

    private void initEvent() {
        mActionView.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //上一步
                ProjectManager.getInstance().goLastStep();
                finish();
            }
        });

        mActionView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //下一步
                goNextStep();
            }
        });

    }

    private void goNextStep() {
        ProjectManager.getInstance().goNextStep();
        if (ProjectManager.getInstance().qrjhqPageEnabled()) {
            //跳转到全热交换器页面
            startActivity(AnnotationUtil.get(ProjectStep6Activity.class));
        }
        else if (ProjectManager.getInstance().kqnrsjPageEnabled()) {
            //跳转到空气能热水机页面
            startActivity(AnnotationUtil.get(ProjectStep7Activity.class));
        }
        else {
            //跳转到设备报价页面
            startActivity(AnnotationUtil.get(ProjectStep8Activity.class));
        }
    }

    /**
     *  获取所有的房间数据
     */
    private void loadAllRoomData() {
        Map<String, Object> param = new HashMap<>();
        param.put("pid", ProjectManager.getInstance().getProjectData().getGuidId());

        mProgressDlg = createProgressBarDialog(this, "数据加载中...");
        mProgressDlg.show();

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROJECT_ALL_ROOMS, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetRoomDataResp>() {
            @Override
            public void onSuccess(GetRoomDataResp obj) {
                // 成功
                if (obj.getGetRoomsResult() != null && obj.getGetRoomsResult().size() > 0) {
                    mRoomData.addAll(obj.getGetRoomsResult());
                    loadProjectSWJInfo();
                }
            }

            @Override
            public void onFailure(String response) {
                showMessage("获取房间信息失败，请重试！");
                mProgressDlg.dismiss();
            }
        });

    }


    /**
     *  获取项目中室外机的配置
     */
    private void loadProjectSWJInfo() {
        Map<String, Object> param = new HashMap<>();
        param.put("pid", ProjectManager.getInstance().getProjectData().getGuidId());

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROJECT_SWJINFO, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetSwjDataResp>() {
            @Override
            public void onSuccess(GetSwjDataResp obj) {
                // 成功
                mSwjData.clear();
                mQuickAdapter.clear();
                mSwjData.addAll(obj.getGetSwjInfosResult());
                mQuickAdapter.addAll(obj.getGetSwjInfosResult());
                mProgressDlg.dismiss();
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                showMessage("获取房间信息失败，请重试！");
            }
        });

    }


    /**
     * 修改室外机的房间信息
     * @param data
     */
    private void modifyProjectSWJInfo(SwjData data) {
        Map<String, Object> param = new HashMap<>();
        param.put("swjInfoData", data);

        mProgressDlg = createProgressBarDialog(this, "修改系统配置中...");
        mProgressDlg.show();

        BasicHttpClient.httpPostAsync(HttpConstant.HTTP_POST_PROJECT_ONE_SWJINFO, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetSwjDataResp>() {
            @Override
            public void onSuccess(GetSwjDataResp obj) {
                //需要重新拉取所有的系统数据
                Map<String, Object> param1 = new HashMap<>();
                param1.put("pid", ProjectManager.getInstance().getProjectData().getGuidId());

                BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROJECT_SWJINFO, AccountManager.getInstance().getToken(), param1, new HttpCallbackHandle<GetSwjDataResp>() {
                    @Override
                    public void onSuccess(GetSwjDataResp obj) {
                        // 成功
                        mProgressDlg.dismiss();
                        mSwjData.clear();
                        mQuickAdapter.clear();
                        mSwjData.addAll(obj.getGetSwjInfosResult());
                        mQuickAdapter.addAll(obj.getGetSwjInfosResult());
                    }

                    @Override
                    public void onFailure(String response) {
                        mProgressDlg.dismiss();
                        showMessage("获取房间信息失败，请重试！");
                    }
                });
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                showMessage("修改室外机系统失败！");
            }
        });

    }

    /**
     *  添加一套室外机系统
     */
    private void addOneProjectSWJInfo() {
        String url = HttpConstant.HTTP_PUT_PROJECT_ONE_SWJINFO
                + "?tk=" + AccountManager.getInstance().getToken()
                + "&pid=" + ProjectManager.getInstance().getProjectData().getGuidId();

        final SwjData data = new SwjData();
        ArrayList<String> rm = new ArrayList<>();

        data.setGuidId(null);
        int count = mSwjData.size() + 1;
        data.setName("系统" + count);
        data.setArea(0);
        data.setLoad(0);
        data.setSwjId(Constant.EMPTY_DEVICE_ID);
        data.setXh(null);
        data.setRooms(rm);
        mProgressDlg = createProgressBarDialog(this, "添加新配置中...");
        mProgressDlg.show();


        Map<String, Object> param = new HashMap<>();
        param.put("swjInfoData", data);

        BasicHttpClient.httpPutAsync(url, param, new HttpCallbackHandle<GetSwjDataResp>() {
            @Override
            public void onSuccess(GetSwjDataResp obj) {
                // 成功
                mProgressDlg.dismiss();
                data.setGuidId(obj.getCreateSwjInfoResult());
                mSwjData.add(data);
                mQuickAdapter.add(data);
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                showMessage("添加室外机失败，请重试！");
            }
        });
    }

    /***
     * 对轻型商用空调自动选型
     */
    private void getSwjDefaultDevice(final SwjData data) {
        if (StringUtils.isEmpty(ProjectManager.getInstance().getProjectDefaultSeries(ProjectInfoData.MACHINE_TAG_FOR_SWJ))) {
            IOSAlertView.showAlertView(ProjectStep5Activity.this, "提示", "没有获取到默认型式，自动选型失败！", "确认", null);
            return;
        }

        mProgressDlg = createProgressBarDialog(ProjectStep5Activity.this, "自动选型中...");
        mProgressDlg.show();
        Map<String, Object> param = new HashMap<>();
        param.put("siid", data.getGuidId());
        param.put("xlid", ProjectManager.getInstance().getProjectDefaultSeries(ProjectInfoData.MACHINE_TAG_FOR_SWJ));

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_SWJ_DEFAULT_DEVICE, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetSwjDataResp>() {
            @Override
            public void onSuccess(GetSwjDataResp obj) {
                // 成功
                mProgressDlg.dismiss();
                if (obj.getAutoSwjEquipResult() != null) {
                    mQuickAdapter.clear();
                    int index = mSwjData.indexOf(data);
                    mSwjData.remove(index);
                    mSwjData.add(index, obj.getAutoSwjEquipResult());
                    mQuickAdapter.addAll(mSwjData);
                } else {
                    IOSAlertView.showAlertView(ProjectStep5Activity.this, "提示", "超出该系列能力范围，请选择其他合适型式。", "确认", null);
                }
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                IOSAlertView.showAlertView(ProjectStep5Activity.this, "提示", "超出该系列能力范围，请选择其他合适型式。", "确认", null);
            }
        });
    }



    /**
     * 回调
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != this.RESULT_OK) {
            return;
        }
        if (requestCode == Select_Swj) {
            if (data != null) {
                ArrayList<GuidData> arrayData = data.getParcelableArrayListExtra("device");
                if (arrayData != null && arrayData.size() > 0) {
                    GuidData selectData = arrayData.get(0);
                    mCurrentSwj.setSwjId(selectData.getGuidId());
                    mCurrentSwj.setXh(selectData.getName());
                    modifyProjectSWJInfo(mCurrentSwj);
                }
            }
        }
        else if (requestCode == Select_Swj_Xl) {
            if (data != null) {
                List<GuidData> xl = data.getParcelableArrayListExtra("device");
                if (xl != null && xl.size() > 0) {
                    //开始自动选型
                    ProjectManager.getInstance().setProjectDefaultSeries(ProjectInfoData.MACHINE_TAG_FOR_SWJ, xl.get(0).getGuidId());
                    getSwjDefaultDevice(mCurrentSwj);
                }
            }
        }
    }

}
